export default class Cache {
    private count: number;
    private max: number;
    private queue: string[];
    private map: {[index: string]: any};

    constructor(maxCount?: number) {
        this.count = 0;
        this.max = maxCount == undefined ? 128 : maxCount;
        this.queue = [];
        this.map = {};
    }

    get(key: string): any {
        let idx = this.queue.indexOf(key);
        if (idx != -1) {
            this.queue.splice(idx, 1);
            this.queue.push(key);
            return this.map[key];
        }
        else return undefined;
    }

    put(key: string, value: any): void {
        let idx = this.queue.indexOf(key);
        if (idx == -1) {
            this.count++;
            while(this.count > this.max) {
                const k = this.queue.shift();
                if (k) delete this.map[k];
                this.count--;
            }
        } else {
            this.queue.splice(idx, 1);
        }
        this.queue.push(key);
        this.map[key] = value;
    }

    remove(key: string): any {
        let idx = this.queue.indexOf(key);
        if (idx == -1) return undefined;
        this.count--;
        this.queue.splice(idx, 1);
        return delete this.map[key];
    }

    clear(): void {
        this.count = 0;
        this.queue = [];
        this.map = {};
    }

    size(): number {
        return this.count;
    }

    capacity(newCapacity?: number): number | undefined {
        if (newCapacity != undefined) this.max = newCapacity;
        else return this.max;
    }
}